package plugins.openform;

import com.cloudera.impala.dsi.dataengine.filters.IFilter;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.events.BeforeCreateListDataProviderArgs;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.mvc.list.ListDataProvider;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.EventObject;

/**
 * 标准单据列表插件
 */
public class OpenDeliverHistory extends AbstractListPlugin implements Plugin {

    {
        // 初始化插件时可以进行一些设置或日志记录
        this.getView().showTipNotification("OpenDeliverHistory 插件已加载");
    }

    @Override
    public void setFilter(SetFilterEvent e) {
        super.setFilter(e);

        // 1. 获取入口参数
        String identity = this.getView().getFormShowParameter().getCustomParam("Identity");

        this.getView().showTipNotification("AAA");

        // 2. 检查参数是否为"user"
        if ("user".equals(identity)) {

            this.getView().showTipNotification("当前身份: " + identity);

            // 3. 获取当前用户名
            String currentUser = RequestContext.get().getUserName();

            // 4. 检查是否存在配送记录
            boolean hasDeliveryRecord = checkDeliveryRecordExists(currentUser);

            if (hasDeliveryRecord) {
                // 5. 存在记录：添加过滤当前用户的订单历史
                QFilter userFilter = new QFilter("dcb4_delivery", QFilter.equals, currentUser);
                e.addCustomQFilter(userFilter);
            } else {
                // 6. 不存在记录：显示空列表并提示
                this.getView().showTipNotification("当前用户不是配送员");
                QFilter emptyFilter = new QFilter("id", QFilter.equals, "-1"); // 永远不匹配的过滤条件
                e.addCustomQFilter(emptyFilter);
            }
        }
    }

    private boolean checkDeliveryRecordExists(String username) {
        // 查询配送单中是否存在该用户的记录
        String selectFields = "id";
        QFilter filter = new QFilter("dcb4_username", QFilter.equals, username);

        return QueryServiceHelper.exists("dcb4_delivery", new QFilter[]{filter});
    }
}